import { queryOrder } from "@xiaoe/etransaction";
import { Toast } from "vant";
import { jumpTool } from "@xiaoe/h5-jump-fe";
import { clearOrderCache } from "../utils/index";

//支付回调
export class PayBackHandler {
  constructor(paySuccessUrl, payFailUrl, order, isAliveCurrentPage = false) {
    this.paySuccessUrl = paySuccessUrl;
    this.payFailUrl = payFailUrl;
    this.isAliveCurrentPage = isAliveCurrentPage;
    this.order = order;
  }
  perform() {
    const { trade_id, order_id } = this.order;
    const params = {
      app_id: window.APPID,
      trade_id,
      order_id,
    };
      return new Promise((resolve, reject) => {
          queryOrder(params)
              .then((data) => {
                  clearOrderCache();
                  const payOrderState = data.info.pay_state;
                  if (payOrderState === "SUCCESS") {
                      if (this.isAliveCurrentPage) {
                          resolve()
                      } else {
                          setTimeout(() => {
                              jumpTool.jumpTargetUrl({
                                  url: decodeURIComponent(this.paySuccessUrl),
                                  isReplace: true,
                              });
                          }, 800);
                      }
                  } else {
                      return Promise.reject(data);
                  }
              })
              .catch((err) => {
                  console.error(err);
                  Toast("您的订单未完成支付，请重新支付");
                  if (this.isAliveCurrentPage) {
                      reject();
                  } else {
                      jumpTool.jumpTargetUrl({
                          url: decodeURIComponent(this.payFailUrl),
                          isReplace: true,
                      });
                  }
              });
      })
  }
}
